﻿// **********************************************************************
//
// Author: KingSley
// Email:3268374537@qq.com
// Created:	2018/8/1   11:35
// Introduce: 摄像机的控制方式，第三人称不可控摄像机
//
// **********************************************************************
using UnityEngine;

namespace KingSley
{
    [AddComponentMenu("KingARPG/摄像机/第三人称固定摄像机")]
    /// <summary>
    /// 固定摄像机和人物的距离
    /// </summary>
    public class CameraInTheThirdPerson : MonoSingleton<CameraInTheThirdPerson>
    {
        /// <summary>
        /// 观察目标
        /// </summary>
        public Transform Target;
        /// <summary>
        /// 观察距离
        /// </summary>
        public float Distance = 3.0F;
        /// <summary>
        /// 观察高度
        /// </summary>
        public float Hight = 3.0F;
        /// <summary>
        /// 跟随的摄像机（主摄像机）
        /// </summary>
        private Camera FollowCamera;
        /// <summary>
        /// 期待摄像机状态
        /// </summary>
        private float WantHight = 0.0f;
        private float WantRotation = 0.0f;
        /// <summary>
        /// 摄像机当前状态
        /// </summary>
        private float CurrentHight = 0.0f;
        private float CurrenRotation = 0.0f;
        /// <summary>
        /// 位置临时存储变量
        /// </summary>
        private Transform Temp_transform;
        private Vector3 CPosition;

        void Awake()
        {
            FollowCamera = Camera.main;
            Temp_transform = FollowCamera.transform;
        }

        void Update()
        {
            if (Target != null)
            {
                WantHight = Target.position.y + Hight;
                CurrentHight = Temp_transform.position.y;
                CurrenRotation = Temp_transform.eulerAngles.y;

                CurrentHight = Mathf.Lerp(CurrentHight, WantHight, 0.9f * Time.deltaTime);

                Quaternion euler = Quaternion.Euler(0.0f, CurrenRotation, 0.0f);
                CPosition = Target.position - (euler * Vector3.forward) * Distance;
                CPosition.y = Hight;

                transform.position = CPosition;
                transform.LookAt(Target);
            }
        }
    }
}
